<template>
  <div class="fx-tree">
    <fx-tree-item :data="treeValue" :is-checked="isChecked"></fx-tree-item>
  </div>
</template>

<script lang="ts">
import { defineComponent, onBeforeMount, PropType, ref } from 'vue'

export interface TreeData {
  id: string | number;
  label: string;
  fxTreeId?: string;
  showChildren?: boolean;
  checked?: boolean;
  checkedAll?: boolean;
  children?: TreeData[];

  [propsName: string]: unknown;
}

interface TreeProps {
  data: TreeData[];
  defaultExpandedKeys: Array<string | number>;
  defaultCheckedKeys: Array<string | number>;
  isChecked: boolean;
}

export default defineComponent({
  name: 'FTree',
  props: {
    data: {
      type: Array as PropType<TreeData[]>,
      required: true
    },
    defaultExpandedKeys: {
      type: Array as PropType<Array<string | number>>,
      default: null
    },
    defaultCheckedKeys: {
      type: Array as PropType<Array<string | number>>,
      default: null
    },
    isChecked: {
      type: Boolean as PropType<boolean>,
      default: false
    }
  },
  setup (props: TreeProps) {
    // 树 数据
    const treeValue = ref<TreeData[]>(props.data)
    // 给数据添加id属性
    const addTreeId = (arr: TreeData[], id = ''): void => {
      arr.forEach((item: TreeData, index: number) => {
        item.fxTreeId = `${id === '' ? '' : id + '-'}${index + 1}`
        if (!item.checked) item.checked = props.defaultCheckedKeys?.includes(item.id)
        if (props.defaultExpandedKeys && props.defaultExpandedKeys.length) {
          item.showChildren = props.defaultExpandedKeys.some((child: string | number) => item.id === child)
        }
        if (item.children && item.children.length) {
          if (item.checked) {
            item.children.forEach((child: TreeData) => {
              child.checked = true
            })
          }
          item.showChildren = false
          addTreeId(item.children, item.fxTreeId)
        }
      })
    }

    onBeforeMount(() => {
      addTreeId(treeValue.value)
    })

    return {
      treeValue
    }
  }
})
</script>
